<?php

namespace app\common\model;

use think\Model;
use traits\model\SoftDelete;

class UserScoreLog extends Model
{

    // 表名
    protected $name = 'user_score_log';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    protected static function init()
    {
        // 插入记录之前更新会员余额
        UserScoreLog::beforeInsert(function ($data) {
            return self::change_score($data);
        });
    }
    protected static function change_score($data){
        $user = model('user')->get($data['user_id']);
        if(empty($user))
        {
            return false;
        }

        // 类型为支出，判断余额是否足够
        if($data['style'] == 2)
        {
            if($user['score'] < $data['score'])
            {
                return false;
            }

            $res = model('user')->where('id', $user['id'])->setDec('score', $data['score']);
        }else{
            $res = model('user')->where('id', $user['id'])->setInc('score', $data['score']);
        }
        if(!$res)
        {
            return false;
        }
    }


}
